package net.zigin.nhi.waste.view.alarm;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.siberiadante.titlelayoutlib.TitleBarLayout;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.AlarmAdapter;
import net.zigin.nhi.waste.adapter.IActivityAlarmType;
import net.zigin.nhi.waste.adapter.NoDataAdapter;
import net.zigin.nhi.waste.bean.AlarmBean;
import net.zigin.nhi.waste.bean.BatchInBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;
import net.zigin.nhi.waste.view.widget.AlarmTypeDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.paperdb.Paper;
import io.reactivex.Observable;

/**
 * 告警信息界面
 */
public class AlarmActivity extends AppCompatActivity {

    private TitleBarLayout mTitle;
    private RecyclerView mRvAlarm;
    private SmartRefreshLayout mRefresh;

    private AlarmAdapter adapter;
    private NoDataAdapter noDataAdapter = new NoDataAdapter();
    private Map<String, Object> map = new HashMap<>();
    private List<AlarmBean> beanList = new ArrayList<>();

    private String alarmType;

    private int page = 1;
    private int limit = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);
        initView();
        initListener();
    }

    private void initView() {
        ImmersionBar.with(this).init();
        mTitle = findViewById(R.id.title);
        mRvAlarm = findViewById(R.id.rv_alarm);
        mRefresh = findViewById(R.id.refresh);
        mRvAlarm.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initListener() {
        mTitle.setRightTextClickListener(v -> {
            AlarmTypeDialog dialog = AlarmTypeDialog.getInstance(this, AlarmActivity.this, mRvAlarm, adapter, dd);
            dialog.show();
        });
        mRefresh.autoRefresh();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        //获取筛选对话框中选中项对应的值
        alarmType = Paper.book().read(Constants.ALARM_TYPE);
        if (StringUtil.isNotEmpty(alarmType)) {
            map.put("type", alarmType);
        } else {
            map.remove("type");
        }

        mRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                beanList.clear();
                page = 1;
                //获取筛选对话框中选中项对应的值
                alarmType = Paper.book().read(Constants.ALARM_TYPE);
                if (StringUtil.isNotEmpty(alarmType)) {
                    map.put("type", alarmType);
                } else {
                    map.remove("type");
                }
                getAlarm();
            }
        });

        mRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                map.put("isPage", true);
                map.put("pageIndex", page);
                map.put("pageSize", limit);
                alarmType = Paper.book().read(Constants.ALARM_TYPE);
                if (StringUtil.isNotEmpty(alarmType)) {
                    map.put("type", alarmType);
                } else {
                    map.remove("type");
                }
                Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                        .getAlarmList(Paper.book().read(Constants.TOKEN), map);
                HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                    @Override
                    protected void success(String data) {
                        if (StringUtil.isNotEmpty(data)) {
                            Log.i("告警列表", data);
                            List<AlarmBean> newList = JSONArray.parseArray(data, AlarmBean.class);
                            if (newList != null && newList.size() > 0) {
                                beanList.addAll(newList);
                                adapter.notifyData(beanList);
                            }
                            if (beanList.size() < limit) {
                                mRefresh.finishLoadMoreWithNoMoreData();
                            } else {
                                mRefresh.finishLoadMore();
                                page++;
                            }
                        } else {
                            mRefresh.finishLoadMoreWithNoMoreData();
                        }
                    }
                });
            }
        });
    }

    /**
     * 接收筛选对话框选择的类型，更新adapter数据源
     */
    private IActivityAlarmType dd = new IActivityAlarmType() {
        @Override
        public void upDataUi(List<AlarmBean> list) {
            if (list != null && list.size() > 0) {
                beanList.clear();
                beanList.addAll(list);
            }
        }
    };

    /**
     * 获取告警列表
     */
    private void getAlarm() {
        map.put("isPage", true);
        map.put("pageIndex", page);
        map.put("pageSize", limit);
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .getAlarmList(Paper.book().read(Constants.TOKEN), map);
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @Override
            protected void success(String data) {
                if (StringUtil.isNotEmpty(data)) {
                    Log.i("告警列表", data);
                    beanList = JSONArray.parseArray(data, AlarmBean.class);
                    if (beanList != null && beanList.size() > 0) {
                        adapter = new AlarmAdapter(beanList);
                        mRvAlarm.setAdapter(adapter);
                        page++;
                    } else {
                        mRvAlarm.setAdapter(noDataAdapter);
                    }
                } else {
                    mRvAlarm.setAdapter(noDataAdapter);
                }
                mRefresh.finishRefresh();
            }

            @Override
            public void error(String msg) {
                super.error(msg);
                mRefresh.finishRefresh();
                mRvAlarm.setAdapter(noDataAdapter);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AlarmTypeDialog.mInstance = null;
        Paper.book().delete(Constants.ALARM_TYPE);
    }
}